<?php

declare(strict_types=1);


namespace App\Resource\Service;
use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Model\AppGoodsModel;
use App\Resource\Model\AppShareModel;
use App\Resource\Model\CartModel;
use App\Resource\Model\GoodsModel;
use App\Resource\Model\StoreShopModel;
use App\Resource\Model\SystemModel;
use Hyperf\Di\Annotation\Inject;

class ShareService extends BaseService
{
    /**
     * 商品是否有效 0有效商品 1无效商品
     */
    const GOODS_STATUS_0 = 0;
    const GOODS_STATUS_1 = 1;
    /**
     *  1次日达
     */
    const CART_SOURCE_1 = 1;
    /**
     * @Inject()
     * @var GoodsService
     */
    private $goodsService;

    /**
     *  app分享勾选
     * @param int $goodsId
     * @param int $shop_id
     * @param int $isSelected
     * @return bool
     */
    public static function isSelected(int $goodsId,int $shop_id,int $isSelected)
    {

        $cartObj = AppGoodsModel::query()->where(['goods_id' => $goodsId,'shop_id' => $shop_id])->first();
        $update = ['is_selected'=>$isSelected];
        if ($cartObj) {
            if (AppGoodsModel::query()->where('goods_id',$goodsId)->where('shop_id',$shop_id)->update($update)) {
                return true;
            } else {
                return false;
            }
        } else {
            $updateOrAddData=['goods_id' => $goodsId,'shop_id' => $shop_id,'is_selected'=>$isSelected];
            if (AppGoodsModel::query()->insert($updateOrAddData)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 获取分享商品选中数量
     *
     * @param int $shop_id
     * @return int
     */
    public function getCartGoodsNumber(int $shop_id)
    {
        $num = intval(AppGoodsModel::query()->where('shop_id', $shop_id)->where('is_selected', 1)->count('*'));
        return $num;
    }

    /**
     * 分享商品信息
     * @param int $shop_id
     * @return array
     */
    public function dataShareList(int $shop_id)
    {
        $res = AppGoodsModel::query()->where('shop_id', $shop_id)->where('is_selected', 1)->get()->toArray();
        $goods_id = array_column($res,'goods_id');
        $isSelected = array_column($res,'is_selected','goods_id');
        $type = 0;
        if ($type == self::GOODS_STATUS_0) {
            $goodsId = GoodsModel::query()
                ->whereIn('id', $goods_id)
                ->where(['is_deleted' => 0, 'status' => 1, 'is_next_day'=>'1'])
                ->whereRaw('!FIND_IN_SET(?,crd_shop_ids)', [$shop_id])
                ->pluck('id')
                ->toArray();
        }
        $types = 1;
        if($types == self::GOODS_STATUS_1) {
            $failureGoodsId = GoodsModel::query()
                ->whereRaw("(FIND_IN_SET({$shop_id},crd_shop_ids) OR is_deleted = 1 OR status = 0 OR is_next_day = '0')")
                ->whereIn('id',$goods_id)
                ->pluck('id')
                ->toArray();
        }
        $goodsList = GoodsService::getCrdGoodsInfoData($goodsId);
        $goodsIds = implode(',',$goodsId);
        $field = ['goodsids' =>$goodsIds];
        AppShareModel::query()->where('shop_id', $shop_id)->update($field);
        $fields = ['is_selected' => 0];
        if($failureGoodsId){
            AppGoodsModel::query()->where('shop_id', $shop_id)->whereIn('goods_id',$failureGoodsId)->update($fields);
        }
        foreach ($goodsList as &$v) {
            $v['is_selected'] = $isSelected[$v['id']] ?? 0;
        }
        return $goodsList;
    }

    /**
     * 分享
     * @param int $shop_id
     * @return array
     */
    public function dataShare(int $shop_id){
        $res = AppGoodsModel::query()->where('shop_id', $shop_id)->where('is_selected', 1)->get()->toArray();
        $goods_id = array_column($res,'goods_id');
        $goodsIds = implode(',',$goods_id);
        $data = StoreShopModel::query()->where('shop_id', $shop_id)->get()->first();
        $shop_name = $data['shop_name'];
        $address = $data['address'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $_goodsListArr = GoodsService::getCrdGoodsInfoData($goods_id);
        $goodsListArr = array_column($_goodsListArr, null, 'goods_id');
        $goods_pick_time = array_column($goodsListArr,'goods_pick_time');
        $time = max($goods_pick_time)??0;
        $list =[
            'shop_id' => $shop_id,
            'shop_name' => $shop_name,
            'address' => $address,
            'longitude' => $longitude,
            'latitude' => $latitude,
            'time' => $time,
            'goodsids' => implode(',',$goods_id),
            'create_at' => date('Y-m-d H:i:s')
        ];
        $obj = AppShareModel::query()->where('shop_id',$shop_id)->first();
        $field =[
            'goodsids' => $goodsIds ,
            'create_at' => date('Y-m-d H:i:s'),
            'time' => $time
        ];
        if ($obj){
            AppShareModel::query()->where('shop_id', $shop_id)->update($field);
        }else{
            AppShareModel::query()->insert($list);

        }
        $create_at = date('Y-m-d');
        $id = AppShareModel::query()->where('shop_id', $shop_id)->value('id');
        $ids='pages/share-list/share-list?id='.$id;
        $field = ['share_title','share_img'];
        $dataRes = SystemModel::query()->whereIn('name', $field)->select(['name','value'])->get()->toArray();
        $resArr = array_column($dataRes, 'value','name');
        $add =[
            'id' => $ids,
            'title' => $resArr['share_title'].' '.$create_at,
            'img' => $resArr['share_img'],
        ];
        return $add;
    }

    /**
     * api分享
     * @param int $mid
     * @param int $id
     * @return array|bool
     */
    public function apiShare(int $mid,int $id){
        $res = AppShareModel::query()->where('id',$id )->get()->toArray();
        $shop_id = $res[0]['shop_id'];
        if(!$res){
            return false;
        }
        $goods_id = array_column($res,'goodsids');
        $goodsId = explode(',',$goods_id[0]);
        $obj = ['goods_num','goods_id'];
        $cart_num = CartModel::query()->where(['mid'=>$mid,'shop_id'=>$shop_id,'group_id'=>0,'activity_goods_id'=>0,'source'=>2])->whereIn('goods_id',$goodsId)->get($obj)->toArray();
        $num = array_column($cart_num,'goods_num','goods_id');
        $field = ['is_selected'=>0];
        CartModel::query()->where(['mid'=>$mid,'shop_id'=>$shop_id,'source'=>2])->update($field);
        $fields = ['is_selected'=>1];
        CartModel::query()->where(['mid'=>$mid,'shop_id'=>$shop_id,'source'=>2,'group_id'=>0,'activity_goods_id'=>0])->whereIn('goods_id',$goodsId)->where('goods_num','>',0)->update($fields);
        $goods_list = $this->goodsService->getCrdGoodsInfoData($goodsId);
        $cut_off_time = SystemModel::query()->where('name','=','cut_off_time')->value('value');
        $sharetime =implode(array_column($res,'create_at'));
        $create_at = (substr($sharetime,0,strpos($sharetime, ' ')));
        $cut_off_time= $create_at.' '.$cut_off_time.':00';
        $atime = strtotime($cut_off_time);
        $add = SystemModel::query()->select(['name','value'])->get()->toArray();
        $data = array_column($add, 'value','name');
        $res[0]['cut_off_time'] = $atime;
        $res[0]['share_img'] = $data['share_img'];
        $res[0]['share_title'] = $data['share_title'].' '.$create_at;
        $res[0]['time'] = date('Y-m-d',strtotime('+1 day')).' '.$res[0]['time'];
        foreach ($goods_list as &$v) {
            $v['cart_num'] = $num[$v['id']] ?? 0;
            $v['price_selling'] = bcmul($v['price_selling'],'100');
            $v['price_market'] = bcmul($v['price_market'],'100');
            $v['goods_pick_time'] = date('Y-m-d',strtotime('+1 day')).' '.$v['goods_pick_time'];
        }

        return [
            'code' => ErrorCode::SUCCESS,
            'data' => [
                'title' => $res,
                'goodslist' => $goods_list,
            ],
        ];
    }
    /**
     * 次日达分享
     * @return array
     */
    public function shareConfig()
    {
        $resArr = SystemModel::query()->select(['name','value'])->get()->toArray();
        $data = array_column($resArr, 'value','name');
        $res =[
            'share_title' => $data['share_title'],
            'share_img' => $data['share_img']
        ];
        return ['code' => ErrorCode::SUCCESS, 'data' => $res];
    }
}
